﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Domain;
using App.Web.ViewModels;
using App.Web.Utility;
using AutoMapper;
using System.IO;
using System.Drawing;
using App.Core.Extensions;
//using App.Core.Authentication;

namespace App.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Company Admin,Company User")]
    public class ProductImageController : BaseController
    {
		private AppEntities _Context = new AppEntities();

        #region Constructor
        public ProductImageController()
		{
		}

        public ProductImageController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
        #endregion Constructor

        #region Action Methods
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List(int ID = 0)
        {
            Product product = _Context.Products.FirstOrDefault(P => P.ID == ID);
            ViewBag.Product = Mapper.Map<Product, ProductViewModel>(product);
            ViewBag.ProductID = ID;
            return View(getImageList(ID));
        }

        /// <summary>
        /// This Action Method is used to upload the Image
        /// </summary>
        /// <param name="productImage"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult List(HttpPostedFileBase productImage, int productID, int productImageID)
        {
            List<ProductImageViewModel> images = getImageList(productID);
            Product product = _Context.Products.FirstOrDefault(P => P.ID == productID);
            ViewBag.Product = Mapper.Map<Product, ProductViewModel>(product);
            ViewBag.ProductID = productID;

            if (productImage == null)            
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Please select an Image to Upload.";
            else if(!WebUtil.IsValidImageFile(productImage))
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Sorry! The file you selected is not a valid Image file.";
            else if (images.Count == ConfigReader.MaxNumberOfProductImages)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = String.Format("Sorry! You are not allowed to upload more than {0} Images for a Product.", ConfigReader.MaxNumberOfProductImages);
            else
            {                
                int w, h;
                String fileName = ImageManager.SaveTempJpeg(productImage.InputStream, ConfigReader.ProductImageAspectRatio, out w, out h);                
                ViewBag.WidthHeight = String.Format("{0},{1}", w, h);
                ViewBag.CropBoxImageUrl = ImageManager.GetTempImageUrl(fileName);
                ViewBag.ProductImageID = productImageID;
                ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME] = productImage.FileName;
            }
            return View(images);
        }

        [HttpPost]
        public ActionResult CropAndSaveImage(ProductImageViewModel image)
        {
            cropAndSaveImage(image);
            return Json(image);
        }

        [HttpPost]
        public ActionResult DeleteProductImage(int imageId)
        {            
            var productImage = _Context.ProductImages.FirstOrDefault(P => P.ID == imageId);
            if (productImage == null)
                return Json(false);
            else
            {
                if (LoggedInUser.Company.ID != productImage.Product.CompanyID)
                    return Json(false);
                ///Delete from File System
                String thumbPath = Server.MapPath(String.Format("{0}/{1}/{2}", AppConstants.Directories.PRODUCT_IMAGES, productImage.ProductID, productImage.Thumbnail));
                String picture = Server.MapPath(String.Format("{0}/{1}/{2}", AppConstants.Directories.PRODUCT_IMAGES, productImage.ProductID, productImage.Picture));
                if (System.IO.File.Exists(thumbPath))
                    System.IO.File.Delete(thumbPath);

                if (System.IO.File.Exists(picture))
                    System.IO.File.Delete(picture);

                ///Delete from Database
                _Context.DeleteObject(productImage);
                _Context.SaveChanges();
                return Json(true);
            }
        }
        #endregion Action Methods

        #region Helper Methods
        private List<ProductImageViewModel> getImageList(int productID)
        {
            var query = from P in _Context.ProductImages where P.ProductID == productID select P;           
            List<ProductImageViewModel> images = Mapper.Map<List<ProductImageViewModel>>(query);            
            return images;
        }
        private void cropAndSaveImage(ProductImageViewModel viewModel)
        {
            if (viewModel.ProductID > 0)
            {
                ProductImage productImage = _Context.ProductImages.FirstOrDefault(P => P.ID == viewModel.ID);
                if (productImage == null)
                {
                    productImage = new ProductImage();
                    productImage.ProductID = viewModel.ProductID;
                    _Context.AddToProductImages(productImage);
                    _Context.SaveChanges();
                    viewModel.ID = productImage.ID;
                }
                ///Crop the Image
                String sourceImage = Server.MapPath(viewModel.Picture);
                if (System.IO.File.Exists(sourceImage))
                {
                    String[] coords = viewModel.CropProperty.Split(',');
                    viewModel.Width = (int)coords[2].ToFloat();
                    viewModel.Height = (int)coords[3].ToFloat();
                    Rectangle rectangle = new Rectangle((int)coords[0].ToFloat(), (int)coords[1].ToFloat(), viewModel.Width, viewModel.Height);
                    String proposedFileName = Server.MapPath(ImageManager.GetProductImageUrl(viewModel.OriginalFileName, viewModel.ProductID));
                    proposedFileName = ImageManager.GetNextFileName(proposedFileName);
                    String[] fileNames = ImageManager.SaveThumbnail(sourceImage, proposedFileName, rectangle, productImage.ProductID, true, ImageFor.Product);
                    productImage.Width = viewModel.Width;
                    productImage.Height = viewModel.Height;
                    productImage.Picture = Path.GetFileName(fileNames[0]); //String.Format("{0}.jpg", productImage.ID);
                    productImage.Thumbnail = Path.GetFileName(fileNames[1]); //String.Format("{0}_Thumb.jpg", productImage.ID);

                    viewModel.Picture = ImageManager.GetProductImageUrl(productImage.Picture, productImage.ProductID);
                    viewModel.Thumbnail = ImageManager.GetProductImageUrl(productImage.Thumbnail, productImage.ProductID);

                    _Context.SaveChanges();
                }

            }
        }
        #endregion Helper Methods
    }
}
